package com.jrx.anytxn.transaction.job.cmpsCrt.config;

import com.jrx.anytxn.param.mapper.ext.ExtPrProductTableMapper;
import com.jrx.anytxn.transaction.config.AnytxnBatchProperties;
import com.jrx.anytxn.transaction.constant.TransBizConstant;
import com.jrx.anytxn.transaction.entity.AmLoanAccountInfo;
import com.jrx.anytxn.transaction.entity.BtGuaranteeList;
import com.jrx.anytxn.transaction.job.cmpsCrt.step.CmpsCrtPreListener;
import com.jrx.anytxn.transaction.job.cmpsCrt.step.CmpsCrtPreProcessor;
import com.jrx.anytxn.transaction.job.cmpsCrt.step.CmpsCrtPreWriter;
import com.jrx.anytxn.transaction.job.collection.config.CollectionConfiguration;
import org.apache.commons.collections.CollectionUtils;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.batch.MyBatisCursorItemReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.*;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.core.listener.StepExecutionListenerSupport;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.core.step.tasklet.TaskletStep;
import org.springframework.batch.item.support.SynchronizedItemStreamReader;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.SimpleAsyncTaskExecutor;
import org.springframework.transaction.PlatformTransactionManager;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 代偿回购准备作业
 *
 * @author lbz
 */
@Configuration
@EnableConfigurationProperties(AnytxnBatchProperties.class)
public class CmpsCrtPreConfiguration {

    Logger logger = LoggerFactory.getLogger(CollectionConfiguration.class);

    @Resource(name = "bizSqlSessionFactory")
    private SqlSessionFactory sqlSessionFactory;
    @Autowired
    private JobBuilderFactory jobBuilderFactory;
    @Autowired
    private StepBuilderFactory stepBuilderFactory;
    @Autowired
    private AnytxnBatchProperties anytxnBatchProperties;
    @Autowired
    private CmpsCrtPreListener cmpsCrtPreListener;
    @Resource
    private ExtPrProductTableMapper extPrProductTableMapper;
    @Autowired
    private CmpsCrtPreProcessor cmpsCrtPreProcessor;
    @Autowired
    private CmpsCrtPreWriter cmpsCrtPreWriter;
    @Autowired
    private PlatformTransactionManager platformTransactionManager;

    @Bean
    public Job cmpsCrtPreJob() {
        return jobBuilderFactory.get("cmpsCrtPreJob")
                .listener(cmpsCrtPreListener)
                .start(checkCrtPreStep()).on(ExitStatus.FAILED.getExitCode()).end()
                .from(checkCrtPreStep()).on("*").to(cmpsCrtPreStep())
                .build()
                .build();
    }

    @Bean
    public Step checkCrtPreStep() {
        return stepBuilderFactory.get("checkCrtPreStep")
                .tasklet(checkCrtPreTasklet())
                .build();
    }

    @Bean
    public Tasklet checkCrtPreTasklet() {
        return (stepContribution, chunkContext) -> {
            List<String> proIdList = extPrProductTableMapper.findByTableStatusAndGuaranteeFlag(TransBizConstant.STATUS_1,TransBizConstant.YES_FLAG);
            if(CollectionUtils.isEmpty(proIdList)){
                throw new Exception("失败");
            }
            return RepeatStatus.FINISHED;
        };
    }



    @Bean
    public Step cmpsCrtPreStep() {
        return stepBuilderFactory.get("cmpsCrtPreStep")
                .<AmLoanAccountInfo, BtGuaranteeList>chunk(anytxnBatchProperties.getCmpsCrtPreJobConfig().getChunkLimit())//表示一批处理100条记录，数据是逐条发送给processor处理的，处理100条记录后，统一返回给writer进行保存处理
                .reader(cmpsCrtPreReader())
                .processor(cmpsCrtPreProcessor)
                .writer(cmpsCrtPreWriter)
                .transactionManager(platformTransactionManager)
                .taskExecutor(new SimpleAsyncTaskExecutor())
                .throttleLimit(anytxnBatchProperties.getCmpsCrtPreJobConfig().getThrottleLimit())//多线程
                .build();
    }

    @Bean
    @StepScope
    public SynchronizedItemStreamReader<AmLoanAccountInfo> cmpsCrtPreReader() {
        //获取需要代偿回购的产品
        List<String> proIdList = extPrProductTableMapper.findByTableStatusAndGuaranteeFlag(TransBizConstant.STATUS_1,TransBizConstant.YES_FLAG);
        MyBatisCursorItemReader<AmLoanAccountInfo> cursorItemReader = new MyBatisCursorItemReader<>();
        cursorItemReader.setSaveState(false);
        cursorItemReader.setSqlSessionFactory(sqlSessionFactory);
        cursorItemReader.setQueryId("com.jrx.anytxn.transaction.mapper.ext.ExtAmLoanAccountInfoMapper.selectByAccountStatusAndProductIdForBatch");
        Map<String, Object> map = new HashMap<>();
        map.put("accountStatus", TransBizConstant.ACCOUNT_STATUS_2);
        map.put("productIds",proIdList);
        cursorItemReader.setParameterValues(map);

        SynchronizedItemStreamReader<AmLoanAccountInfo> synchronizedItemStreamReader = new SynchronizedItemStreamReader<>();
        synchronizedItemStreamReader.setDelegate(cursorItemReader);
        return synchronizedItemStreamReader;
    }

}
